import {Component} from '@angular/core';
import {App, IonicPage} from 'ionic-angular';
import {FormGroup, FormBuilder, Validators} from "@angular/forms";
import {DialogProvider} from "@providers/dialog";
import {DataQueryServiceProvider} from "@providers/data-query-service/data-query-service";
import {StorageProvider} from "@providers/storage";
import {HttpProvider} from "@providers/http";
import {Observable} from "rxjs/Observable";
import {env} from "@env/environment";
import {Validator} from "@providers/validator";

/**
 * Generated class for the CustomerLoginPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-customer-login',
  templateUrl: 'customer-login.html',
})
export class CustomerLoginPage {

  mode: boolean = env.mode == 'prod';
  tel: any;
  verificationCode: any;
  isSend: boolean = false;
  btnTitle: any = '获取验证码';
  hide: boolean = false;//获取焦点时隐藏下面的图片
  loginForm: FormGroup;

  constructor(private formBuilder: FormBuilder,
              private dialog: DialogProvider,
              private dataQueryService: DataQueryServiceProvider,
              private http: HttpProvider,
              private app: App,
              private storage: StorageProvider) {

    let config = {'tel': ['', [Validators.required, Validator.phone]]};// 第一个参数是默认值
    if (this.mode) config["verificationCode"] = ['', [Validators.required]];
    this.loginForm = this.formBuilder.group(config);
  }

  ionViewDidLoad() {
    this.storage.write("userInfo", null);
  }


  login(_event) {
    _event.preventDefault();//该方法将通知 Web 浏览器不要执行与事件关联的默认动作
    let goToLogin = () => {
      this.dialog.showLoading();
      this.http.post("/trust/Inbound/invoke.do", {
        interfaceId: "csm.qcfwlogin.query",
        data: JSON.stringify({"IDVALUE": this.tel}),
        rmstoken:'127.0.0.1'
      }).subscribe(
        message => {
          this.dialog.hideLoading();
          let userInfo = message.USER;
          userInfo["isLoggedIn"] = true;
          this.storage.write('userInfo', userInfo);
          if (userInfo.ROLETYPEID) {
            console.info("我是经销商");
            this.isDealer(userInfo)
          } else {
            this.app.getRootNav().setRoot('CustomerTabsPage');
          }
        },
        error => {
          this.dialog.hideLoading();
          this.dialog.showAlert('登录失败');
        });
    };

    if (this.mode) {
      this.dataQueryService.getkey(this.tel, this.verificationCode).subscribe(message => {
          if (message.MSGID==='S'&& message.MESSAGE == '验证码验证成功!') {
            goToLogin()
          }else{
            this.dialog.showAlert("验证码错误");
          }
        },
        error => {
          this.dialog.showAlert("验证码错误");
        }
      );
    } else {
      goToLogin()
    }
  }

  /**
   * 判断是否为经销商登录
   * @param UserInfo
   */
  isDealer(UserInfo: any) {
    this.dialog.showConfirm(() => {
      this.app.getRootNav().setRoot(UserInfo.JSSY01);
      console.info("经销商登录成功");
    }, "是否经销商登录？", null, () => {
      this.app.getRootNav().setRoot('CustomerTabsPage');
      console.info("游客登录成功");
    });
  }

  /**
   * 获取验证码
   */
  getVerificationCode() {
    if (this.tel == null || this.tel == '') {
      this.dialog.showAlert('请填写手机号码');
      return;
    }
    if (this.isSend) {
      return;
    }
    this.dialog.showLoading();
    this.http.post("/trust/Inbound/invoke.do", {
      interfaceId: "csm.login.putyzm",
      data: JSON.stringify({'mobile': this.tel})
    }).subscribe(message => {
      this.dialog.hideLoading();
      this.isSend = true;
      let ms = 60;
      let sub = Observable.interval(1000).subscribe(() => {

        ms -= 1;
        this.btnTitle = ms + "秒";
        if (ms == 0) {
          this.btnTitle = '获取验证码';
          this.isSend = false;
          sub.unsubscribe();
        }
      });
      this.dialog.showAlert('获取验证码成功，请耐心等待');
    }, error => {
      this.dialog.showAlert('获取验证码失败!');
      this.dialog.hideLoading();
    });
  }
}
